package model

import (
	"fmt"
	"hanlinyuan_qa/config"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	UserID       int       `gorm:"primaryKey;autoIncrement" json:"user_id"`
	UserName     string    `gorm:"not null" json:"user_name"`
	Password     string    `gorm:"not null" json:"password"`
	IsSuperAdmin bool      `gorm:"not null" json:"is_super_admin"`
	UpdateTime   time.Time `gorm:"null" json:"update_time"`
	CreateTime   time.Time `gorm:"null" json:"create_time"`
	IsDelete     bool      `gorm:"null" json:"is_delete"`
}

type Question struct {
	QuestionID string    `gorm:"primaryKey" json:"question_id"`
	Count      int       `gorm:"not null" json:"count"`
	Content    string    `gorm:"null" json:"content"`
	IsActivate bool      `gorm:"null" json:"is_activate"`
	UpdateTime time.Time `gorm:"null" json:"update_time"`
	CreateTime time.Time `gorm:"null" json:"create_time"`
	IsDelete   bool      `gorm:"null" json:"is_delete"`
}

type Answer struct {
	AnswerID   int       `gorm:"primaryKey;autoIncrement" json:"answer_id"`
	QuestionID string    `gorm:"not null" json:"question_id"`
	IpAddress  string    `gorm:"null" json:"ip_address"`
	IpLocation string    `gorm:"null" json:"ip_location"`
	Content    string    `gorm:"null" json:"content"`
	UpdateTime time.Time `gorm:"null" json:"update_time"`
	CreateTime time.Time `gorm:"null" json:"create_time"`
	IsDelete   bool      `gorm:"null" json:"is_delete"`
}

/**
"{\"leftRefractive\":9,\"rightMirror\":9,\"rightRefractive\":9,\"leftVision\":4.2,\"leftMirror\":9,\"rightVision\":4.2}"
*/

func CreateTable() {
	dsn := config.DB_URL
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	fmt.Println("db = ", db)
	fmt.Println("err = ", err)

	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(10 * time.Second)

	db.AutoMigrate(&User{})
	db.AutoMigrate(&Question{})
	db.AutoMigrate(&Answer{})
}

var db *gorm.DB

func GetDB() *gorm.DB {
	if db == nil {
		dsn := config.DB_URL
		var err error
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
		fmt.Println("db = ", db)
		fmt.Println("err = ", err)
		sqlDB, err := db.DB()
		sqlDB.SetMaxIdleConns(10)
		sqlDB.SetMaxOpenConns(100)
		sqlDB.SetConnMaxLifetime(10 * time.Second)
	}
	return db
}
